#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from __future__ import print_function
import requests
import json
import sys
import os
import codecs
import subprocess
import shutil
import time
import urllib

# 是否是windows平台
win = sys.platform == 'win32'
# 是否是python3
python3 = sys.version > '3'

# URL编码，支持中文
quote = None
if python3:
	quote = urllib.parse.quote
else:
	quote = urllib.quote

# robot程序
robot = "python -m robot" if not python3 else "robot"
# rebot程序
rebot = "rebot" if win and not python3 else "rebot"

# 测试报告输出目录
output_dir = "./result"

# 请求头配置文件
configFile = "modHeader.json"

# windows上执行cmd的编码
cmd_encoding = "gbk" if win else 'utf8'

# webrts服务器地址
webrts_url = "http://127.0.0.1:8346"

# 选择接口url
select_url = webrts_url + "/select"

# finish接口
finish_url = webrts_url + "/collect/finish"

user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36"

headers = {"user-agent" : user_agent,
		   "content-type" : "application/json"}


def post(url, headers, data):
	rsp = requests.post(url, headers=headers, data=data)
	if rsp.status_code != 200:
		print(rsp.content)
		exit(-1)
	return rsp

def encode(data):
	return data.encode(cmd_encoding)

# 设置请求头
def change_header_config(task_id, testcase):
	f = codecs.open(configFile, mode='w+', encoding="utf-8")
	f.write(json.dumps({
		"spec_file_name": quote(testcase.encode("utf8")),
		"job_id": task_id
	}, ensure_ascii=False))
	f.close()


def runCMD(cmd):
	cmd = ' '.join(cmd)
	print(cmd)
	if python3:
		subprocess.run(cmd)
	else:
		os.system(encode(cmd))


# 选择测试并开启依赖信息收集
def select_and_start(task):
	print('headers: ', headers)
	print('json.dumps(task): ', json.dumps(task))

	rsp = post(select_url, headers, json.dumps(task))
	print(rsp.json())
	testcases = rsp.json()["data"]
	if len(testcases) == 0 :
		print("没有测试被选择")
		exit(-1)
	return testcases

# 获取测试名
# testcase是路径
# testname是robot内部的测试名
def get_testname(testcase):
	return testcase.replace(".txt", "").replace(".robot", "").replace("/", ".")

# 获取测试用例输出目录
def get_outputdir(task_id, testcase):
	return output_dir + "/" + task_id + "/"+ get_testname(testcase);

# 创建robot的Argument file
def create_argument_file(task_id, testcase):
	f = codecs.open("argsfile", mode="w+", encoding="utf-8")

	f.write("-d " + get_outputdir(task_id, testcase) + "\n")
	f.write("-s " + get_testname(testcase) + "\n")
	f.write("--variable BrowserrModProxyEnable:True")

	f.close()

# 执行测试
def execute(testdir, task_id, testcases):
	for testcase in testcases:
		if filter(testcase):
			continue
		print("Executing " + testcase)
		change_header_config(task_id, testcase)
		create_argument_file(task_id, testcase)
		cmd = [robot, "-A argsfile", testdir]
		print('cmd: ', cmd)
		runCMD(cmd)


# 结束依赖信息收集re
def finish(task_id):
	print('finish_url: ', finish_url)
	print('{"task": task_id}: ', {"task": task_id})
	rsp = post(finish_url, None, {"task": task_id})
	print(rsp.json())

# 获取测试截图文件路径
def get_img_path(testdir, reportdir, testname):
	suite = os.path.basename(os.path.abspath(testdir))
	return reportdir + "/" + suite + "." + testname.replace("_", " ") + ".jpg"

# 复制文件到目标目录
def copy_file(src, dst):
	if os.path.exists(src):
		print("From " + src + " copy to " + dst)
		shutil.copy(src, dst)
	else:
		print(src + " doesn't exist")

# 合并测试报告
def merge_report(testdir, task_id, testcases):
	cmd = [rebot, "-d", output_dir + "/" + task_id, "-o output.xml", "--merge -N " + task_id]
	for testcase in testcases:
		if filter(testcase):
			continue
		reportdir = get_outputdir(task_id, testcase)
		cmd.append(reportdir + "/*.xml")
		copy_file(get_img_path(testdir, reportdir, get_testname(testcase)), output_dir + "/" + task_id)
	runCMD(cmd)


def filter(testcase):
	return testcase.find(u'init') >= 0 or testcase.find(u'通用方法') >= 0


def get_task_id():
	return time.strftime("T%Y-%m%d-%H%M", time.localtime())

if __name__ == '__main__':
	task = json.loads('''{
	  "artifactInfos": [
	    {
	      "name": "iTrust",
	      "version": "1.0"
	    }
	  ],
	  "newVersion": "v1_0",
	  "oldVersion": "",
	  "projectName": "iTrust",
	  "taskName": "iTrust-1",
	  "testCaseDir": "",
	  "testGit": "https://gitee.com/William-WZL/itrust-test.git",
      "testType": "robot"
	}''')
	task_id = get_task_id()
	task['taskName']  = task_id
	print(task)

	testdir = "D:/itrust/itrust-test-1.0/"
	if len(sys.argv) > 1:
		testdir = sys.argv[1]
	os.chdir(testdir)
	print("Working Directory : " + testdir)

	# testcases = select_and_start(task)
	# print(u"\n选择的测试列表: ")
	# for t in testcases:
	# 	print("\t" + t)

	# if python3:
	# 	goon = input(u"\n是否执行测试(y/n): ")
	# else:
	# 	goon = raw_input(u'\n是否执行测试(y/n): '.encode("GBK"))
	# if goon != "y":
	# 	print(u"直接退出, 不运行测试脚本")
	# 	finish(task_id)
	# 	exit(0)

	# execute(testdir, task_id, testcases)
	finish(task_id)
	# merge_report(testdir, task_id, testcases)
